import { useState, useEffect } from 'react'
import { Swiper, Toast, Grid, Button, SpinLoading, Input } from 'antd-mobile'
import { LocationOutline, RightOutline } from 'antd-mobile-icons'
import styles from './Home.module.css'
import axios from '../../axios'
import { useNavigate } from 'react-router-dom'

const images = [
  '/images/背景图1.jpg',
  '/images/背景图2.jpg',
  '/images/背景图3.jpg',
  '/images/背景图4.jpg'
]

const categories = [
  { icon: '🍇', text: '时令水果' },
  { icon: '🥬', text: '新鲜蔬菜' },
  { icon: '🥚', text: '肉禽蛋类' },
  { icon: '🦐', text: '海鲜水产' },
  { icon: '🏷️', text: '粮油调味' },
  { icon: '🧁', text: '乳品烘焙' },
]

// 定义商品类型
interface Product {
  id: string
  title: string
  image: string
  currentPrice: number
  originalPrice: number
  sales?: number
  stock?: number
  description?: string
  unit?: string
  category?: string
  tags?: string[]
  activity?: string[]
  status?: string
  createdAt?: string
  updatedAt?: string
}

// 购物车商品类型
interface CartItem {
  id: string;
  title: string;
  image: string;
  currentPrice: number;
  originalPrice: number;
  quantity: number;
  category: string;
  tags?: string[];
  activity?: string[];
  stock: number;
  selected: boolean;
}

const items = images.map((image, index) => (
  <Swiper.Item key={index}>
    <div
      className={styles.content}
      onClick={() => {
        Toast.show(`你点击了卡片 ${index + 1}`)
      }}
    >
      <img src={image} alt={`背景${index + 1}`} className={styles.bannerImage} />
    </div>
  </Swiper.Item>
))

export default function Home() {
  const [flashSaleProducts, setFlashSaleProducts] = useState<Product[]>([])
  const [groupBuyProducts, setGroupBuyProducts] = useState<Product[]>([])
  const [isLoadingProducts, setIsLoadingProducts] = useState(false)
  const [countdown, setCountdown] = useState({ hours: 1, minutes: 23, seconds: 9 })
  const navigate = useNavigate()

  // 倒计时函数
  useEffect(() => {
    const timer = setInterval(() => {
      setCountdown(prev => {
        let { hours, minutes, seconds } = prev;
        
        if (seconds > 0) {
          seconds--;
        } else {
          seconds = 59;
          if (minutes > 0) {
            minutes--;
          } else {
            minutes = 59;
            if (hours > 0) {
              hours--;
            } else {
              // 倒计时结束，重置为1小时23分9秒
              hours = 1;
              minutes = 23;
              seconds = 9;
            }
          }
        }
        
        return { hours, minutes, seconds };
      });
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // 格式化时间显示
  const formatTime = (time: number) => {
    return time.toString().padStart(2, '0');
  };

  const fetchFlashSaleProducts = async () => {
    try {
      setIsLoadingProducts(true)
      const response = await axios.get('http://localhost:3000/jjx/getseckillproducts')
      if (response.data.code === 200) {
        console.log('限时秒杀商品：',response.data.data)
        // 过滤掉禁用状态的商品
        const activeProducts = (response.data.data || []).filter((product: Product) => 
          product.status === 'active'
        )
        setFlashSaleProducts(activeProducts)
      }
    } catch (error) {
      console.error('获取秒杀商品失败:', error)
      Toast.show('获取秒杀商品失败')
    } finally {
      setIsLoadingProducts(false)
    }
  }

  // 获取拼团商品数据
  const fetchGroupBuyProducts = async () => {
    try {
      const response = await axios.get('http://localhost:3000/jjx/getgroupproducts',)
      if (response.data.code === 200) {
        console.log('特惠拼团商品：',response.data.data)
        // 过滤掉禁用状态的商品
        const activeProducts = (response.data.data || []).filter((product: Product) => 
          product.status === 'active'
        )
        setGroupBuyProducts(activeProducts)
      }
    } catch (error) {
      console.error('获取拼团商品失败:', error)
      Toast.show('获取拼团商品失败')
    }
  }

  useEffect(() => {
    fetchFlashSaleProducts()
    fetchGroupBuyProducts()
  }, [])



  const handleCategoryClick = (category: { text: string }) => {
    navigate(`/app/class?category=${category.text}`)
  }

  return (
    <div className={styles.home}>
      <div className={styles.header}>
        <img src="/logoo.png" alt="logo" className={styles.logo} />
        <Input placeholder='请输入搜索关键词' className={styles.searchBar} onClick={()=>{
          navigate('/app/shou')
        }}/>
      </div>
      <div className={styles.locationBar}>
        <div className={styles.location} onClick={()=>{
          navigate('/app/xiugaidingwei')
        }}>
          <LocationOutline /> 万达广场店 <RightOutline />
        </div>
      </div>
      <div className={styles.banner}>
        <Swiper
          loop
          autoplay>
          {items}
        </Swiper>
      </div>
      <div className={styles.categories}>
        <Grid columns={6}>
          {categories.map((category, index) => (
            <Grid.Item key={index} onClick={() => handleCategoryClick(category)}>
              <div className={styles.categoryItem}>
                <div className={styles.categoryIcon}>{category.icon}</div>
                <div className={styles.categoryText}>{category.text}</div>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
      <div className={styles.flashSale}>
        <div className={styles.flashSaleHeader}>
          <div className={styles.flashSaleTitle}>
            <span>限时秒杀</span>
            <span className={styles.flashSaleTime}>{formatTime(countdown.hours)} : {formatTime(countdown.minutes)} : {formatTime(countdown.seconds)}</span>
          </div>
          <div className={styles.flashSaleMore} onClick={()=>{
            navigate('/xian')
          }}>
            查看全部 <RightOutline />
          </div>
        </div>
        <div className={styles.flashSaleProducts}>
          {flashSaleProducts.map(product => (
            <div key={product.id} className={styles.flashSaleProduct}>
              <div className={styles.productImage}>
                <img src={product.image} alt={product.title} />
              </div>
              <div className={styles.productName}>{product.title}</div>
              <div className={styles.productPrice}>
                <span className={styles.currentPrice}>¥{product.currentPrice}</span>
                <span className={styles.originalPrice}>¥{product.originalPrice}</span>
              </div>
              <Button 
                className={styles.addToCartButton}
                onClick={() => {
                  // 添加到购物车
                  const cartItem = {
                    id: product.id,
                    title: product.title,
                    image: product.image,
                    currentPrice: product.currentPrice,
                    originalPrice: product.originalPrice,
                    quantity: 1,
                    category: product.category || '',
                    tags: product.tags || [],
                    activity: product.activity || [],
                    stock: product.stock || 10,
                    selected: true
                  };
                  
                  // 从 localStorage 获取现有购物车
                  const existingCart = localStorage.getItem('cart');
                  let cartItems = existingCart ? JSON.parse(existingCart) : [];
                  
                  // 检查商品是否已在购物车中
                  const existingItemIndex = cartItems.findIndex((item: CartItem) => item.id === product.id);
                  
                  if (existingItemIndex >= 0) {
                    // 如果已存在，增加数量
                    cartItems[existingItemIndex].quantity += 1;
                  } else {
                    // 如果不存在，添加新商品
                    cartItems.push(cartItem);
                  }
                  
                  // 保存到 localStorage
                  localStorage.setItem('cart', JSON.stringify(cartItems));
                  
                  Toast.show('已添加到购物车');
                  navigate('/app/cars');
                }}
              >
                加入购物车
              </Button>
            </div>
          ))}
        </div>
      </div>
      <div className={styles.groupBuy}>
        <div className={styles.groupBuyHeader}>
          <div className={styles.groupBuyTitle}>
            <span>特惠拼团</span>
            <span className={styles.groupBuyCount}>已拼团{groupBuyProducts.length > 0 ? groupBuyProducts[0].sales || 0 : 0}件</span>
          </div>
          <div className={styles.groupBuyMore} onClick={()=>{
            navigate('/pin')
          }}>
            查看全部 <RightOutline />
          </div>
        </div>
        <div className={styles.groupBuyProducts}>
          {groupBuyProducts.map(product => (
            <div key={product.id} className={styles.groupBuyProduct}>
              <div className={styles.productImage}>
                <img src={product.image} alt={product.title} />
              </div>
              <div className={styles.productInfo}>
                <div className={styles.groupTag}>3人团</div>
                <div className={styles.productName}>{product.title}</div>
                <div className={styles.groupPrice}>
                  <span className={styles.priceLabel}>拼团价:</span>
                  <span className={styles.currentPrice}>¥{product.currentPrice}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {isLoadingProducts && (
        <div className={styles.loadingOverlay}>
          <SpinLoading color='primary' />
          <span className={styles.loadingText}>加载中...</span>
        </div>
      )}


    </div>
  )
}
